# -*- coding: utf-8 -*-
from flask import Flask, render_template, jsonify, request
import os
from aliyun_qwen_integration import QwenAPI

app = Flask(__name__, static_folder='static', template_folder='templates')

# 初始化阿里云百炼大模型API
qwen_api = QwenAPI()

@app.route('/')
def index():
    """网站首页"""
    return render_template('index.html')

@app.route('/character_network')
def character_network():
    """人物关系网络"""
    return render_template('character_network.html')

@app.route('/word_frequency')
def word_frequency():
    """词频统计"""
    return render_template('word_frequency.html')

@app.route('/topic_evolution')
def topic_evolution():
    """主题演化分析"""
    return render_template('topic_evolution.html')

@app.route('/sentiment_analysis')
def sentiment_analysis():
    """情感分析"""
    return render_template('sentiment_analysis.html')

@app.route('/qa')
def qa():
    """智能问答页面"""
    return render_template('qa.html')

@app.route('/generation')
def generation():
    """文本生成页面"""
    return render_template('generation.html')

@app.route('/api/character_network_data')
def character_network_data():
    """获取人物关系网络数据"""
    # 这里应该调用实际的数据分析函数
    # 暂时返回示例数据
    data = {
        "nodes": [
            {"name": "贾宝玉", "symbolSize": 80},
            {"name": "林黛玉", "symbolSize": 65},
            {"name": "薛宝钗", "symbolSize": 60}
        ],
        "links": [
            {"source": "贾宝玉", "target": "林黛玉"},
            {"source": "贾宝玉", "target": "薛宝钗"}
        ]
    }
    return jsonify(data)

@app.route('/api/ask', methods=['POST'])
def ask_question():
    """处理用户提问"""
    data = request.json
    question = data.get('question', '')
    
    if not question:
        return jsonify({'answer': '请输入问题'})
    
    # 调用阿里云百炼大模型回答问题
    answer = qwen_api.ask_question(question)
    return jsonify({'answer': answer})

@app.route('/api/generate', methods=['POST'])
def generate_text():
    """生成红楼梦风格文本"""
    data = request.json
    topic = data.get('topic', '')
    length = data.get('length', '短篇')
    
    if not topic:
        return jsonify({'text': '请输入写作主题'})
    
    # 调用阿里云百炼大模型生成文本
    generated_text = qwen_api.generate_hongloumeng_style_text(topic, length)
    return jsonify({'text': generated_text})

if __name__ == '__main__':
    app.run(debug=True)